/*	Copyright 2008 Jacquemin Valentin

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
	
	@author pollux
 */
package org.poxd.persistance;

import java.io.Serializable;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.poxd.model.Language;

/**
 * @author pollux
 * 
 */
public class LanguageDAO extends AbstractDAO {
	private static Logger log = Logger.getLogger(LanguageDAO.class);

	/**
	 * Retrieve the list of all the languages
	 * 
	 * @return java.util.List filled by
	 * @see org.poxd.model.Category
	 */
	@SuppressWarnings("unchecked")
	public List<Language> listContain() {
		startOperation();
		List list = session.createQuery("from Language as l order by l.name")
				.list();
		endOperation();
		return list;
	}

	/**
	 * Add a language in the database
	 * 
	 * @param language
	 */
	public Serializable addLanguage(Language language) {
		Serializable l = null;
		startOperation();
		session.clear();
		if (!languageExist(language)) {
			l = session.save(language);
			log.debug("LANGUAGE SAVED " + language);
		}
		endOperation();
		return l;
	}

	private boolean languageExist(Language language) {
		Query q = session
				.createQuery("from Language as l where l.name = :name");
		q.setString("name", language.getName());
		if (q.list().size() > 0) {
			return true;
		}
		log.debug("LANGUAGE DOES NOT EXIST");
		return false;
	}

	public void delete(Language selected) throws SniwePersistanceException {
		startOperation();
		try {
			log.debug("DELETE LANGUAGE " + selected);
			session.delete(selected);
		} catch (HibernateException e) {
			throw new SniwePersistanceException(e);
		}
		endOperation();
	}

}
